import { SessionKey } from '@/util/session';
import { useModel } from '@@/exports';
import { getUserInfo } from '@/services/system/user';
import initRouters from '../../config/routers/init';
import { formatRouter } from '@/util/util';

export interface FetchUserInfoType extends USER_TYPE.UserInfoRet {
  pathList: string[];
}

export const fetchUserInfo = async (): Promise<FetchUserInfoType> => {
  const ret = await getUserInfo({
    skipErrorHandler: true, //跳过错误处理
  });
  let pathList: string[] = [];
  let menu: FetchUserInfoType['menu'] = [];
  //过滤掉顶级菜单
  if (ret.data.menu && ret.data.menu.length > 0) {
    menu = ret.data.menu[0].children;
  }
  const route = [...initRouters, ...menu];
  const lastRouters = await formatRouter(route);
  pathList = lastRouters.pathList;
  ret.data.menu = lastRouters.list;
  return {
    ...ret.data,
    pathList,
  };
};
const useUserInfo = () => {
  const { setInitialState } = useModel('@@initialState');
  const saveUserInfo = (loginRet: USER_TYPE.LoginRet, call?: () => void) => {
    const { expiresIn, token, refreshToken, tokenHead } = loginRet;
    sessionStorage.setItem(SessionKey.TOKEN, token);
    sessionStorage.setItem(SessionKey.REFRESH_TOKEN, refreshToken);
    sessionStorage.setItem(SessionKey.EXPIRES_IN, String(expiresIn));
    sessionStorage.setItem(SessionKey.TOKEN_HEAD, tokenHead);
    fetchUserInfo().then((r) => {
      setInitialState((s) => ({
        ...s,
        currentUser: r.user,
        roleList: r.role,
        menuList: r.menu,
        pathList: r.pathList,
      })).finally(() => {
        call?.();
      });
    });
  };

  const removeUserInfo = () => {
    for (let key of Object.keys(SessionKey)) {
      sessionStorage.removeItem(key);
    }
    setInitialState((s) => ({ ...s, currentUser: undefined }));
  };

  return {
    saveUserInfo,
    removeUserInfo,
  };
};
export default useUserInfo;
